import pinyin from 'pinyin';

// 过滤函数
function filterByPinyin(data, keyword) {
  const pinyinres = pinyin(data, {
    style: 'normal', // 使用普通风格的拼音
  }).join('');
  // 检查拼音是否包含关键字
  return pinyinres.includes(keyword);
}

// 根据字符串筛选出匹配的项的函数
function filterTree(trees, searchString, route) {
  const whitenames = route?.routes
    ?.filter((it) => it.name)
    ?.map((it) => it.name);

  if (!searchString) return trees;

  return trees
    ?.filter((it) => it.name)
    .map((item) => {
      if (
        item?.name?.includes?.(searchString) ||
        filterByPinyin(item?.name, searchString) ||
        whitenames.includes(item.name)
      ) {
        return { ...item };
      }

      const children = filterTree(item.children || [], searchString, route);
      if (children.length > 0) {
        return { ...item, children };
      }
      return undefined;
    })
    .filter((item) => item);
}

//找到当前节点
function findNodeById(trees, targetId) {
  let tree = [trees];

  let result = null;
  function recursiveSearch(node) {
    if (node.path === targetId) {
      result = node;
      return;
    }

    if (node.routes && node.routes.length > 0) {
      for (const child of node.routes) {
        recursiveSearch(child);
        if (result) {
          return;
        }
      }
    }
  }

  // 从树的根节点开始搜索
  for (const node of tree) {
    recursiveSearch(node);
    if (result) {
      break;
    }
  }
  result = {
    ...result,
  };
  return result;
}

export { filterTree, findNodeById };
